<template>
  <div>
    <!-- <button @click="wx">wxpay</button> -->
    <Nav message="-1" />

    <van-tabs v-model="active" scrollspy sticky>
      <van-tab title="商品">
        <van-swipe v-show="swipeShow">
          <van-swipe-item v-for="(image, index) in spuSwipeImages" :key="index">
            <img width="100%" :src="image" />
          </van-swipe-item>
        </van-swipe>
        <!-- spu标题 -->
        <van-cell>{{ productSpu.spuTitle }}</van-cell>
        <van-cell style="font-weight: bold"
          >￥{{ productSpu.spuPriceBetween }}</van-cell
        >
        <van-cell style="font-weight: bold"
          >运费：￥{{ productSpu.freight }}</van-cell
        >
      </van-tab>

      <van-tab title="规格"
        ><van-cell-group>
          <van-cell v-for="(item, index) in prodtctSpuSpecs" :key="index">
            <van-col span="6" style="font-size: 0.8rem">{{
              item.spuSpecsName
            }}</van-col>
            <van-col
              span="18"
              style="padding-left: 0.5rem; font-size: 0.8rem"
              >{{ item.spuSpecsValue }}</van-col
            >
          </van-cell>
        </van-cell-group></van-tab
      >

      <van-tab title="详情">
        <span v-for="item in productSpuDetailImages.length" :key="item">
          <img :src="productSpuDetailImages[item - 1].img" width="100%" />
        </span>
      </van-tab>
    </van-tabs>

    <!-- 购买弹窗 -->
    <van-sku
      v-model="buyShow"
      :sku="sku"
      :goods="goods"
      @buy-clicked="onBuyClicked"
      :initial-sku="initialSku"
      @sku-selected="skuSelected"
      @sku-prop-selected="skuPropSelected"
      @sku-reset="skuReset"
    >
      <!-- 自定义 sku-header-price -->
      <template #sku-header-price="props">
        <div class="van-sku__goods-price" style="color: rosybrown">
          <span class="van-sku__price-symbol"><b>￥</b></span
          ><span class="van-sku__price-num">{{ props.price }}</span>
        </div>
      </template>

      <!-- 自定义按钮 -->
      <template #sku-actions="props">
        <div class="van-sku-actions">
          <!-- <van-button
            square
            size="large"
            type="warning"
            color="rosybrown"
            @click="addCard"
          >
            加入购物车
          </van-button> -->

          <div @click="addCard" style="width: 100%">
            <van-button
              square
              size="large"
              type="danger"
              @click="props.skuEventBus.$emit('sku:buy')"
              color="rosybrown"
            >
              加入购物车
            </van-button>
          </div>

          <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
          <van-button
            square
            size="large"
            type="danger"
            @click="props.skuEventBus.$emit('sku:buy')"
            color="rosybrown"
          >
            立即购买
          </van-button>
        </div>
      </template>
    </van-sku>

    <!-- 底部导航 -->
    <van-goods-action>
      <!-- <van-goods-action-icon icon="chat-o" text="客服" />
      <van-goods-action-icon icon="shop-o" text="店铺" /> -->
      <van-goods-action-button
        color="rosybrown"
        type="warning"
        text="加入购物车"
        @click="buy"
      />
      <van-goods-action-button
        color="rosybrown"
        type="danger"
        text="立即购买"
        @click="buy"
      />
    </van-goods-action>
  </div>
</template>
<script>
import Nav from "@/components/Nav.vue";
import { Toast } from "vant";
export default {
  components: {
    Nav,
  },
  created() {
    let spuId = this.$route.query.spuId;
    // console.log('item：'+spuId)
    const _this = this;
    axios
      .get(this.$api + "product/findItemBySpuId/" + spuId)
      .then(function (resp) {
        _this.sku = resp.data.data.sku;
        _this.goods = resp.data.data.goods;
        _this.productSpu = resp.data.data.productSpu;
        _this.spuSwipeImages = resp.data.data.spuSwipeImages;
        _this.productSpuDetailImages = resp.data.data.productSpuDetailImages;
        _this.prodtctSpuSpecs = resp.data.data.prodtctSpuSpecs;
        _this.initialSku = resp.data.data.initialSku;
      });
  },
  data() {
    return {
      addCardFlag: true, //点击弹窗里的加入购物车时 变为false，就不会执行vant回调onBuyClicked方法
      productSpu: {
        // spuId: 1,
        // spuTitle:
        //   "CASEJOLY Designed for iPhone 12 Pro Max Case 6.7 Inch [Military Grade Drop Protection] Translucent Matte Hard PC Back & TPU Bumper, Shockproof Protective & Slim, Fit for iPhone",
        // spuPriceBetween: "10000.00",
        // freight: 10,
      },
      active: 0,
      spuSwipeImages: [
        // "../static/imac-white-1.png",
        // "../static/imac-white-2.png",
      ],
      productSpuDetailImages: [
        // {
        //   img: "../static/imac-gray-details-1.png",
        // },
        // {
        //   img: "../static/imac-gray-details-2.png",
        // },
        // {
        //   img: "../static/imac-gray-details-3.png",
        // },
        // {
        //   img: "../static/imac-gray-details-4.png",
        // },
      ],
      swipeShow: true, //轮播
      prodtctSpuSpecs: [
        // {
        //   spuSpecsName: "显示屏\n",
        //   spuSpecsValue:
        //     "27 英寸 (对角线) 5K 视网膜显示屏<br>分辨率为 5120 x 2880 像素，支持十亿色彩",
        // },
        // {
        //   spuSpecsName: "处理器\n",
        //   spuSpecsValue:
        //     "3.8GHz 8 核第十代 Intel Core i7 处理器 (Turbo Boost 最高可达 5.0GHz)",
        // },
      ],
      buyShow: false, //立即购买
      sku: {
        // tree: [
        //   {
        //     k: "颜色", // skuKeyName：规格类目名称
        //     k_s: "s1", // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
        //     v: [
        //       {
        //         id: "1", // skuValueId：规格值 id
        //         name: "银色", // skuValueName：规格值名称
        //         previewImgUrl: "../static/imac-white-1.png", // 用于预览显示的规格类目图片
        //       },
        //       {
        //         id: "2",
        //         name: "灰色",
        //         previewImgUrl: "../static/imac-gray-1.png",
        //       },
        //     ],
        //   },
        //   {
        //     k: "图形处理器", // skuKeyName：规格类目名称
        //     k_s: "s2", // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
        //     v: [
        //       {
        //         id: "1", // skuValueId：规格值 id
        //         name: "Radeon Pro Vega 56 图形处理器，配备 8GB HBM2 显存", // skuValueName：规格值名称
        //       },
        //       {
        //         id: "2",
        //         name: "Radeon Pro Vega 64 图形处理器，配备 16GB HBM2 显存",
        //       },
        //       {
        //         id: "3",
        //         name: "Radeon Pro Vega 64X 图形处理器，配备16GB HBM2 显存",
        //       },
        //     ],
        //   },
        // ],
        // list: [
        //   {
        //     id: 2259, // skuId
        //     s1: "1", // 规格类目 k_s 为 s1 的对应规格值 id
        //     s2: "1",
        //     s3: "",
        //     s4: "",
        //     price: 1, // 价格（单位分）
        //     stock_num: 110, // 当前 sku 组合对应的库存
        //   },
        //   {
        //     id: 2259, // skuId
        //     s1: "1", // 规格类目 k_s 为 s1 的对应规格值 id
        //     s2: "2",
        //     s3: "",
        //     s4: "",
        //     price: 3100033, // 价格（单位分）
        //     stock_num: 900, // 当前 sku 组合对应的库存
        //   },
        //   {
        //     id: 2259, // skuId
        //     s1: "1", // 规格类目 k_s 为 s1 的对应规格值 id
        //     s2: "3",
        //     s3: "",
        //     s4: "",
        //     price: 3100033, // 价格（单位分）
        //     stock_num: 900, // 当前 sku 组合对应的库存
        //   },
        //   {
        //     id: 225, // skuId
        //     s1: "2", // 规格类目 k_s 为 s1 的对应规格值 id
        //     s2: "1",
        //     s3: "",
        //     s4: "",
        //     price: 5000055, // 价格（单位分）
        //     stock_num: 100, // 当前 sku 组合对应的库存
        //   },
        //   {
        //     id: 225, // skuId
        //     s1: "2", // 规格类目 k_s 为 s1 的对应规格值 id
        //     s2: "2",
        //     s3: "",
        //     s4: "",
        //     price: 5100055, // 价格（单位分）
        //     stock_num: 700, // 当前 sku 组合对应的库存
        //   },
        //   {
        //     id: 225, // skuId
        //     s1: "2", // 规格类目 k_s 为 s1 的对应规格值 id
        //     s2: "3",
        //     s3: "",
        //     s4: "",
        //     price: 5100055, // 价格（单位分）
        //     stock_num: 700, // 当前 sku 组合对应的库存
        //   },
        // ],
        // price: "0.00", // 默认价格（单位元）
        // stock_num: 220, // 商品总库存
        // // collection_id: 2261, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        // none_sku: false, // 是否无规格商品
        // // hide_stock: false, // 是否隐藏剩余库存
      },
      goods: {
        // 默认商品 sku 缩略图
        // picture: "../static/0.png",
        // picture: "this.sku.tree.v[0].previewImgUrl",
      },
      //默认选中
      initialSku: {
        // s1: "1",
        // s2: "1",
      },
      cardDetail: {
        isOpt: 1, //自己定义的
        spuId: null,
        skuId: null,
        spuName:
          null,
        freight: null, //运费
        num: null,
        price: null,//10000.33
        icon: null,
        amount: null, //总价 30010.333
        skuTag: [],
        token:null
      },

      onBuySkuInfo: [], //点击弹窗的加入购物车或购买的sku内部事件
    };
  },
  methods: {
    addCard() {
      console.log("点击加入购物车");
      this.addCardFlag = false;
console.log(this.initialSku)


      // console.log("")
      // console.log()

      //将不等于 null 和 '' 的s1-s6 放进一个数组
      let s1s6arr = [];
      let count = 0;
      if (
        this.onBuySkuInfo.selectedSkuComb.s1 != "" &&
        this.onBuySkuInfo.selectedSkuComb.s1 != null &&
        this.onBuySkuInfo.selectedSkuComb.s1 != undefined
      ) {
        s1s6arr[count] = this.onBuySkuInfo.selectedSkuComb.s1;
        count += 1;
      }

      if (
        this.onBuySkuInfo.selectedSkuComb.s2 != "" &&
        this.onBuySkuInfo.selectedSkuComb.s2 != null &&
        this.onBuySkuInfo.selectedSkuComb.s2 != undefined
      ) {
        s1s6arr[count] = this.onBuySkuInfo.selectedSkuComb.s2;
        count += 1;
      }
      if (
        this.onBuySkuInfo.selectedSkuComb.s3 != "" &&
        this.onBuySkuInfo.selectedSkuComb.s3 != null &&
        this.onBuySkuInfo.selectedSkuComb.s3 != undefined
      ) {
        s1s6arr[count] = this.onBuySkuInfo.selectedSkuComb.s3;
        count += 1;
      }
      if (
        this.onBuySkuInfo.selectedSkuComb.s4 != "" &&
        this.onBuySkuInfo.selectedSkuComb.s4 != null &&
        this.onBuySkuInfo.selectedSkuComb.s4 != undefined
      ) {
        s1s6arr[count] = this.onBuySkuInfo.selectedSkuComb.s4;
        count += 1;
      }
      if (
        this.onBuySkuInfo.selectedSkuComb.s5 != "" &&
        this.onBuySkuInfo.selectedSkuComb.s5 != null &&
        this.onBuySkuInfo.selectedSkuComb.s5 != undefined
      ) {
        s1s6arr[count] = this.onBuySkuInfo.selectedSkuComb.s5;
        count += 1;
      }
      if (
        this.onBuySkuInfo.selectedSkuComb.s6 != "" &&
        this.onBuySkuInfo.selectedSkuComb.s6 != null &&
        this.onBuySkuInfo.selectedSkuComb.s6 != undefined
      ) {
        s1s6arr[count] = this.onBuySkuInfo.selectedSkuComb.s6;
        count += 1;
      }
      //   console.log("s1s6arr")
      // console.log(s1s6arr)

if(this.sku.tree.length > 0 ){


      //找出点击的sku图片
      for (let index = 0; index < this.sku.tree[0].v.length; index++) {
        if (
          this.sku.tree[0].v[index].id == this.onBuySkuInfo.selectedSkuComb.s1
        ) {
          this.cardDetail.icon = this.sku.tree[0].v[index].previewImgUrl;
        }
      }




      let skuTagCount = 0;
      //找出点击sku的标签
      for (let index = 0; index < this.sku.tree.length; index++) {
        for (let j = 0; j < 6; j++) {
          if (this.sku.tree[index].v[j] != null) {
            if (this.sku.tree[index].v[j].id == s1s6arr[skuTagCount]) {
              this.cardDetail.skuTag[skuTagCount] = this.sku.tree[index].v[
                j
              ].name;
              skuTagCount += 1;
            }
          }
        }
      }
      console.log("this.cardDetail.skuTag");
      console.log(this.cardDetail.skuTag);


}

      if(this.cardDetail.icon == '' || this.cardDetail.icon == null){
        this.cardDetail.icon = this.spuSwipeImages[0]
      }
      // console.log("this.cardDetail.icon")
      // console.log(this.cardDetail.icon)


      // console.log(this.onBuySkuInfo);
      this.cardDetail.spuId = this.productSpu.spuId;
      this.cardDetail.skuId = this.onBuySkuInfo.selectedSkuComb.skuId;
      this.cardDetail.spuName = this.productSpu.spuTitle;
      this.cardDetail.freight = this.productSpu.freight;
      this.cardDetail.num = this.onBuySkuInfo.selectedNum;
      this.cardDetail.price = this.onBuySkuInfo.selectedSkuComb.price; //单位分
      this.cardDetail.amount = this.onBuySkuInfo.selectedSkuComb.price*this.onBuySkuInfo.selectedNum+(this.productSpu.freight*100);

console.log('this.cardDetail')
console.log(this.cardDetail)
let token = this.$cookie.get("shoptoken");
if (token == null) {
  this.$router.push({
    path: "/login",
    query: { item: this.$route.path },
  });
}
this.cardDetail.token = token

const _this = this;
var newAddressJSON = JSON.stringify(_this.newAddress);
axios
  .post(this.$api + "card/saveItemGoCard", _this.cardDetail, {
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
    },
  })
  .then(function (resp) {
              if (resp.data.code == 0) {
            let instance = Toast("添加成功");
            setTimeout(() => {
              instance.close();
            }, 1000);
          }
  });



















    },

    //点击底部加入购物车或购买的弹窗
    buy() {
      this.buyShow = true;
    },
    //弹窗立即购买按钮
    onBuyClicked(item) {
      console.log(item);
      this.onBuySkuInfo = item;

      // this.$store.state.specsId[0] = item.selectedSkuComb.s1;
      // this.$store.state.specsId[1] = item.selectedSkuComb.s2;
      // this.$store.state.quantity = item.selectedNum;

      this.timer = setTimeout(() => {
        //设置延迟执行
        console.log("ok");
        if (this.addCardFlag) {
          let skuObject = { skuId: null, skuNum: null };
          skuObject.skuId = item.selectedSkuComb.skuId;
          skuObject.skuNum = item.selectedNum;
          this.$store.state.detailGoAddressSkuId = skuObject.skuId;
          this.$store.state.detailGoAddressSkuNum = skuObject.skuNum;

          // this.$router.push("/orderDetail");
          this.$router.push({
            path: "/orderDetail",
            query: { skuId: skuObject.skuId, skuNum: skuObject.skuNum },
          });
        }
      }, 10);
      this.addCardFlag = true;
    },
    skuPropSelected() {
      // alert("1");
    },
    skuSelected(item) {
      // alert("2");
      console.log("skuSelected方法：" + item);
    },
    skuReset() {
      // alert("3");
    },
    // wx() {
    //   axios.get("https://eeee.utools.club/wx/pay").then(function (resp) {
    //     console.log(resp.data["mweb_url"]);
    //     window.location.href = resp.data["mweb_url"];
    //   });
    // },
  },
};
</script>
<style scope>
/* 弹窗 */
.van-sku-row__item {
  background: rgb(221, 171, 171);
  color: #000;
}
</style>